package com.woniu.project.sentinel.exception;


import com.woniu.project.core.exception.ErrorResult;
import com.woniu.project.core.exception.ProjectException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.time.LocalDateTime;

/**
 * 异常处理
 * @Author: Klaus
 * @Date: 2020/9/27 20:16
 */
@RestControllerAdvice
@Slf4j
public class GlobleExceptionHandler {

    //TODO 还需添加其他的异常处理 例如 等400 403 405 。。。。。（认证相关 url相关 参数相关等）
    @ExceptionHandler(value = ProjectException.class)
    public ResponseEntity<ErrorResult> errorHandler(ProjectException e){
        log.error("出现异常:{},时间:{},说明:{}",e.getClass().getName(), LocalDateTime.now().toString(),e.getMessage());

        ErrorResult errorResult = new ErrorResult();
        errorResult.setCode(e.getCode());
        errorResult.setMsg(e.getMessage());
        return new ResponseEntity(errorResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = Exception.class)
    public ResponseEntity<ErrorResult> errorHandler(Exception e){
        log.error("出现异常:{},时间:{},说明:{},Stack:[{}]",e.getClass().getName(), LocalDateTime.now().toString(),e.getMessage(),getstackTrace(e));

        ErrorResult errorResult = new ErrorResult();
        errorResult.setCode(500);
        errorResult.setMsg(e.getMessage());
        return new ResponseEntity(errorResult, HttpStatus.INTERNAL_SERVER_ERROR);
    }


    //得到堆栈信息的字符串
    private String getstackTrace(Exception e) {
        StringBuffer sbs = new StringBuffer();
        for(StackTraceElement st : e.getStackTrace()) {
            sbs.append(st.toString()).append( "\r\n");
        }
        return sbs.toString();
    }

}
